package javB;
import java.io.*;
import java.util.*;
public class ab {
    public static void main(String[] args) {
        File file = new File("C:\\Users\\19449\\Desktop\\products.txt");
        Scanner sc = null;
        int count = 0;
        double sum = 0;

        try {
            sc = new Scanner(file);
            // 跳过第一行（商品列表标题）
            if (sc.hasNextLine()) {
                sc.nextLine();
            }
            // 读取每一行数据
            while (sc.hasNextLine()) {
                String line = sc.nextLine().trim();
                if (!line.isEmpty()) {
                    // 分割字符串，提取价格部分
                    String[] parts = line.split(",");
                    if (parts.length == 2) {
                        String priceStr = parts[1].trim();
                        // 提取数字部分并转换为double
                        double price = Double.parseDouble(priceStr.split("元")[0].trim());
                        count++;
                        sum += price;
                        System.out.println("商品价格: " + price);
                    }
                }
            }

            // 计算平均价格
            double averagePrice = sum / count;
            String formattedAverage = String.format("%.2f", averagePrice);
            System.out.println("平均价格: " + formattedAverage + " 元");

            // 追加写入平均价格到文件
            try (FileWriter writer = new FileWriter(file, true)) {
                writer.write("\n平均价格: " + formattedAverage + " 元\n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sc != null) {
                sc.close();
            }
        }
    }
}


